const express = require('express');
const utility = require('utility');
const jsonwebtoken = require('jsonwebtoken');
const router = express.Router();
const path = require('path');
const db = require(path.join(__dirname, '../utils', 'db.js'));

router.post('/reguser', async function (req, res) {
    req.body.password = utility.md5(req.body.password);
    let r = await db('insert into user set ?', req.body);
    if (r && r.affectedRows == 1) {
        res.send({ status: 0, message: '注册成功' });
    } else {
        res.send({ status: 1, message: '注册失败' })
    }
});

router.post('/login', async function (req, res) {
    let username = req.body.username;
    let password = utility.md5(req.body.password);
    let r = await db('select * from user where username = ? and password = ?', [username, password]);
    if (r && r.length > 0) {
        res.send({
            status: 0,
            message: '登录成功',
            token : 'Bearer ' + jsonwebtoken.sign(
                {username : req.body.username, id : r[0].id},
                'biggerevent',
                {expiresIn : '2 days'}
            )
        });
    } else {
        res.send({ status: 1, message: '登录失败' });

    }
})

module.exports = router;